<template>
	<view class="page-container">
		<view class="box-container">
			<ActiveForm ref="activeForm" v-model="form" :formData="formData"></ActiveForm>
		</view>
		<view class="box-container" v-if="form.delivery && form.delivery !== ''">
			<ActiveForm ref="activeForm2" v-model="form2" :formData="formData2"></ActiveForm>
		</view>
		<view class="box-container-button">
			<uv-button size="large" color="linear-gradient(to bottom, #167fff, #4b8aff)"
				customStyle="color:#ffffff;fontWeight:500;fontSize:16px" @click="submit">保存</uv-button>
		</view>
		<view class="box-container-button">
			<uv-button size="large" color="#e9e9e9" customStyle="color:#333333;fontWeight:500;fontSize:16px"
				@click="submit">取消</uv-button>
		</view>
	</view>
</template>

<script>
	import ActiveForm from "@/component/active-form/active-form.vue";
	import address from "@/assets/address.json";
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools'
	export default {
		components: {
			ActiveForm
		},
		data() {
			return {
				apiKey: '',
				SecretKey: '',
				base64str: '',
				//双向绑定回显
				form: {},
				form2: {},
				//表单配置项
				formData: [{
						id: "kjjn123sasd",
						placeholder: "请输入名字",
						label: "姓名",
						type: "text",
						disabled: false,
						rules: {
							name: "name",
							value: "",
							verify: true,
							errMess: "姓名未填写",
						},
					},
					{
						id: "uisd123fjks",
						placeholder: "请输入手机号",
						label: "手机号",
						type: "mobile",
						rules: {
							name: "mobile",
							value: "", //字段值
							verify: true,
							errMess: "手机号格式不正确",
						},
						oneKeyPhone: true, //是否开启微信点击获取手机号
						//微信获取手机号回调  和参数oneKeyPhone配套  由于小程序props传递函数会丢失（此处无效） 方法在目录active-form/mixins.js中自定义书写
						// getphonenumber({details}) {
						//
						// }
					},
					{
						id: "ukhjgas12dsas",
						placeholder: "请选择配送方式",
						label: "配送方式",
						type: "select",
						show: false, //是否显示
						title: "请选择配送方式",
						list: [{
							value: 1,
							name: "配送上门",
						}],
						rules: {
							name: "delivery",
							value: "", //list.value  0 1
							verify: false,
							errMess: "配送方式未选择",
						},
					}
				],
				formData2: []
			};
		},

		mounted() {
			// 初始化区域列表（支持N级区域）
			this.initFormData();
		},
		watch: {
			// 监听区域选择的变化
			form2: {
				deep: true,
				handler(newForm2) {
					this.updateChildAreas(newForm2);
				}
			}
		},
		methods: {
			// 递归初始化表单结构
			initFormData() {
				this.formData2 = this.generateAreaForm(address.list, 1);
			},

			// 递归生成区域表单项
			generateAreaForm(data, level) {
				if (!data || data.length === 0) return [];

				return [{
						id: `area${level}`,
						placeholder: `请选择${level}级区域`,
						label: `${level}级区域`,
						type: "select",
						show: true,
						title: `请选择${level}级区域`,
						list: data.map((item, index) => ({
							value: index + 1, // 以索引作为 value
							name: item.name
						})),
						rules: {
							name: `area${level}`,
							value: "",
							verify: false,
							errMess: `请选择${level}级区域`,
						}
					},
					...this.generateAreaForm(data[0]?.childrens || [], level + 1) // 递归添加子区域
				];
			},

			// 查找当前选择的区域数据
			findSelectedAreaData(areaList, level, selectedValues) {
				let data = areaList;
				for (let i = 1; i < level; i++) {
					const selectedValue = selectedValues[`area${i}`];
					if (!selectedValue) return [];
					const selectedItem = data[selectedValue - 1]; // 因为value从1开始
					data = selectedItem?.childrens || [];
				}
				return data;
			},

			// 更新下一级的区域列表
			updateChildAreas(newForm2) {
				for (let level = 1; level < this.formData2.length; level++) {
					const selectedValue = newForm2[`area${level}`];
					if (selectedValue) {
						const nextLevel = level + 1;
						const nextData = this.findSelectedAreaData(address.list, nextLevel, newForm2);

						if (this.formData2[nextLevel - 1]) {
							this.formData2[nextLevel - 1].list = nextData.map((item, index) => ({
								value: index + 1,
								name: item.name
							}));
							if (!nextData.length) {
								this.form2[`area${nextLevel}`] = "";
							}
						}
					} else {
						// 选项变更后，清空后续区域
						for (let j = level + 1; j <= this.formData2.length; j++) {
							this.form2[`area${j}`] = "";
							if (this.formData2[j - 1]) {
								this.formData2[j - 1].list = [];
							}
						}
						break;
					}
				}
			},
			findSelectedAreaName(areaKey, value) {
				const level = parseInt(areaKey.replace("area", ""), 10); // 提取区域等级
				const areaList = this.findSelectedAreaData(address.list, level, this.form2);

				const selectedItem = areaList[value - 1]; // value 从 1 开始
				return selectedItem ? selectedItem.name : "";
			},
			// 提交表单
			submit() {
				Promise.all([
						this.$refs.activeForm.vervify(),
						this.form.delivery ? this.$refs.activeForm2.vervify() : Promise.resolve(this.form2)
					])
					.then(([form1, form2]) => {
						// 复制数据
						let finalFormData = {
							...form1,
							...form2
						};

						// 替换区域字段的值，将索引转换为地区名称
						Object.keys(finalFormData).forEach((key) => {
							if (key.startsWith("area")) {
								finalFormData[key] = this.findSelectedAreaName(key, finalFormData[key]);
							}
						});

						const deliveryOption = this.formData.find(item => item.rules.name === "delivery");
						if (deliveryOption) {
							const selectedDelivery = deliveryOption.list.find(option => option.value === finalFormData
								.delivery);
							if (selectedDelivery) {
								finalFormData.delivery = selectedDelivery.name;
							}
						}

						console.log("最终提交的数据:", finalFormData);
						this.$store.dispatch('updateAddressList', finalFormData);
						// 这里可以提交 finalFormData
						uni.navigateTo({
							url: '/pages/takeaway/addressList'
						});
					})
					.catch(err => {
						console.log("表单校验未通过", err);
					});
			}

		},
	}
</script>

<style lang="scss" scoped>
	.page-container {
		background-color: #f6f7f9;
		min-height: 100vh;
		overflow: hidden;

		.box-container {
			background-color: #ffffff;
			margin: 24rpx;
			border-radius: 16rpx;
			padding: 24rpx 32rpx;
		}

		.box-container-button {
			margin: 24rpx;
			border-radius: 16rpx;
			overflow: hidden;
		}
	}
</style>